<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\kuaishou\schema;

use app\command\BaseWork;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\service\batch\KuaiShouBatchService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class SchemaQueueWork extends BaseWork
{
    public const REDIS_TASK_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::BATCH_CONFIG_KEY]['batch_ks_schema_material'];

    protected function configure()
    {
        // 指令配置
        $this->setName('schema_queue');

        // 设置描述
        $this->setDescription('直达链接分发');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->getOutputMessage('直达链接分发开始');

        $redis = Cache::store('redis')->handler();
        $redisKey = self::REDIS_TASK_KEY;

        // 超过5min就停止
        $t = time();
        $runTime = 5 * 60;
        while (time() - $t <= $runTime) {
            $idStr = $redis->lpop($redisKey);
            if (! $idStr) {
                $this->getOutputMessage('暂无数据');
                sleep(rand(5, 10));
                continue;
            }

            $arr = explode('|||', $idStr);
            $advId = $arr[0];
            $type = intval($arr[1]);
            $materialId = $arr[2];

            try {
                $this->getOutputMessage('同步[adv_id:' . $advId . ',type:' . $type . ',material_id:' . $materialId . ']开始');
                if (! KuaiShouBatchService::batchSchemaQueue($advId, $type, $materialId)) {
                    $this->getOutputMessage(KuaiShouBatchService::getError(0));
                }
                $this->getOutputMessage('同步[adv_id:' . $advId . ',type:' . $type . ',material_id:' . $materialId . ']完成');
            } catch (\Exception $e) {
                $this->getOutputMessage($e->getMessage());
                $this->getOutputMessage($e->getFile() . '[' . $e->getLine() . ']');
                $this->getOutputMessage($e->getTraceAsString());
            }
        }

        $this->getOutputMessage('直达链接分发结束');
    }
}
